import { Container, Grid, Paper, Typography } from "@material-ui/core";
import React from "react";
import axios from "axios";
import FileItem, { FileItemProps } from "../components/FileItem";
import Navigator from "../components/Navigator";
import './LandingPage.css';

interface LandingPageState {
    cwd: string[];
    loading: boolean;
    error: boolean;
    items: FileItemProps[];
}

export default class LandingPage extends React.Component<any, LandingPageState> {
    constructor(props: any) {
        super(props);
        this.state = {
            cwd: ['/'],
            loading: true,
            error: false,
            items: []
        };
    }

    componentDidMount() {
        if (this.state.loading) {
            this.loadList();
        }
    }

    render() {
        let content;
        if (this.state.loading) {
            content = (<Typography>Loading...</Typography>);
        } else {
            if (this.state.error) {
                content = (<Typography>Unexpected error</Typography>);
            } else {
                content = this.state.items.map(({name, isDirectory, size, modifyDate}) => <FileItem name={name} isDirectory={isDirectory} size={size} modifyDate={modifyDate} open={this.open.bind(this)}/>).map((it, k) => (<Grid item xs={3} key={k}   >{it}</Grid>));
            }
        }
        return (
            <Container>
                <Paper className={"box"}>
                    <Navigator cwd={this.state.cwd} refresh={() => { this.loadList(this.state.cwd); }} upDir={this.upDir.bind(this)} />
                    <Grid container spacing={2}>
                        {content}
                    </Grid>
                </Paper>
            </Container>
        );
    }

    private open(s: string, d: boolean) {
        const newCwd = this.state.cwd.concat([s]);
        if (d) {
            this.setState({
                cwd: newCwd,
                loading: true
            });
            this.loadList(newCwd);
        } else {
            const a = document.createElement('a');
            a.href = `${process.env.REACT_APP_API_HOST ? `//${process.env.REACT_APP_API_HOST}` : ''}/download?path=${newCwd.join('/')}`;
            a.download = s;
            a.click();
        }
    }

    private upDir() {
        if (this.state.cwd.length === 1) {
            return;
        }
        const newCwd = this.state.cwd.slice(0, this.state.cwd.length - 1);
        this.setState({
            cwd: newCwd,
            loading: true
        });
        this.loadList(newCwd);
    }

    private loadList(cwd: string[] = ['/']) {
        axios.get(`${process.env.REACT_APP_API_HOST ? `//${process.env.REACT_APP_API_HOST}` : ''}/list?path=${cwd.join('/')}`).then(resp => {
            if (resp.data.code === 0) {
                this.setState({
                    loading: false,
                    items: resp.data.message
                });
            } else {
                this.setState({
                    loading: false,
                    error: true
                });
            }
        }).catch(e => {
            console.error(e);
            this.setState({
                loading: false,
                error: true
            });
        });
    }
}
